<template>
  <!--头部区域-->
  <div style="padding: 10px; height: 50px; line-height: 50px; display: flex">
    <div style="flex: 1"></div>
    <div
      style="
        width: 300px;
        display: flex;
        justify-content: center;
        align-items: center;
      "
    >
      <el-button
          type="info"
          style="margin-left: 15px"
          @click="reminderDialogVisible = true"
      >Docker使用说明</el-button
      >
      <el-button
        type="primary"
        color="#fab6b6"
        style="margin-left: 15px"
        @click="addDialogVisible = true"
        >申请Docker</el-button
      >
    </div>
    <el-dialog v-model="addDialogVisible" title="申请Docker" width="30%">
      <el-form :model="addForm" label-width="100px">
        <el-form-item label="Docker名" >
          <el-input v-model.trim="addForm.podName"></el-input>
        </el-form-item>
        <el-form-item label="CPU">
          <el-select v-model="addForm.cpu" placeholder="请选择需要的CPU核心数"  style="width: 275px">
            <el-option label="1核心" :value=1 />
            <el-option label="2核心" :value=2 />
          </el-select>
        </el-form-item>
        <el-form-item label="内存">
          <el-select v-model="addForm.memory" placeholder="请选择需要的内存大小"  style="width: 275px">
            <el-option label="256MB" :value=256 />
            <el-option label="512MB" :value=512 />
          </el-select>
        </el-form-item>
        <el-form-item label="操作系统">
          <el-select v-model="addForm.imageOS" placeholder=""  style="width: 275px" @change="osChange">
            <el-option v-for="item in osOptions"  :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="版本">
          <el-select v-model="addForm.imageVersion" placeholder=""  style="width: 275px">
            <el-option v-for="item in versionOptions"  :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="有效期">
          <el-input v-model.trim.number="addForm.applyTime">
            <template #append>天</template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button type="primary" color="#fab6b6" @click="save"
            >申请</el-button
          >
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="reminderDialogVisible" title="Docker使用说明" width="40%">
      <el-form label-width="55px">
        <el-form-item label="第一步">
          <el-input
              v-model="reminder.first"
              style="width: 100%"
              readonly
          />
        </el-form-item>
        <el-form-item label="第二步" >
          <el-input
              v-model="reminder.second"
              style="width: 100%"
              type="textarea"
              :rows="4"
              readonly
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
              v-model="reminder.remark"
              style="width: 100%"
              type="textarea"
              :rows="4"
              readonly
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button type="primary" color="#fab6b6" @click="reminderDialogVisible = false"
          >关闭</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
  <div style="padding: 10px">
    <el-dialog v-model="reletDialogVisible" title="申请续租" width="30%">
      <el-form :model="reletForm" label-width="100px">
        <el-form-item label="Docker名" >
          <el-input v-model.trim="reletForm.podName" disabled></el-input>
        </el-form-item>
        <el-form-item label="申请续租时长">
          <el-input v-model.trim.number="reletForm.applyTime">
            <template #append>天</template>
          </el-input>

        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button type="primary" color="#fab6b6" @click="relet"
          >申请</el-button
          >
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="deleteDialogVisible" title="注销确认" width="30%">
      <el-form :model="deleteForm" label-width="100px">
        <el-form-item label="Docker名" >
          <el-input v-model.trim="deleteForm.podName" disabled></el-input>
        </el-form-item>
        <el-form-item label="验证用户密码">
          <el-input
              prefix-icon="Lock"
              v-model.trim="deleteForm.password"
              show-password
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button type="primary" color="#fab6b6" @click="deletePod"
          >注销</el-button
          >
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="accessDialogVisible" title="访问权限管理" width="35%">
      <div style="padding: 10px; height: 50px; line-height: 50px; display: flex;justify-content: center;margin-bottom: 10px">
        <el-select
            v-model="newAccess"
            filterable
            remote
            clearable
            placeholder="请输入用户ID"
            :remote-method="find"
            :loading="loading"
            style="width: 240px"
        >
          <el-option
                v-for="item in accessOptions"
                :label="item.userID"
                :value="item.userID"
          >
            <span style="float: left">{{ item.userID }}</span>
            <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px;">
              {{ item.userName }}
            </span>
          </el-option>
        </el-select>
        <div style="flex: 0.1"></div>
        <el-button  @click="access">
          新增授权用户
        </el-button>
        <div style="flex: 0.5"></div>
      </div>
      <div style="text-align: left">
      <el-text size="large">
        <b> 已授权用户: </b>
      </el-text>
      </div>
      <el-table :data="authorizationTableData" :header-cell-style="{'background-color': '#fcf9f4'}">
        <el-table-column prop="userID" label="用户ID" />
        <el-table-column prop="userName" label="用户名" />
        <el-table-column label="操作"  align="center">
          <template #default="scope">
            <el-button  @click="handleDeleteAuthorized(scope.row)">回收权限</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <span>
          <el-button type="primary" color="#fab6b6" @click="accessDialogVisible=false"
          >关闭</el-button
          >
        </span>
      </template>
    </el-dialog>
    <el-table :data="tableData" border="border" empty-text="暂无Docker">
      <el-table-column prop="id" label="DockerID" width="120px" />
      <el-table-column prop="name" label="Docker名" />
      <el-table-column prop="cpu" label="cpu核心数" />
      <el-table-column prop="memory" label="内存(MB)" />
      <el-table-column prop="imageOS" label="操作系统" :formatter=formatOS />
      <el-table-column prop="imageVersion" label="操作系统版本" :formatter=formatVersion />
      <el-table-column prop="nodePort" label="连接端口" />
      <el-table-column prop="expirationTime" label="到期时间" :formatter=formatTime />
      <el-table-column label="操作" width="300px" align="center">
        <template #default="scope">
          <el-button  @click="handleAccess(scope.row)">访问权限管理</el-button>
          <el-button  @click="handleRelet(scope.row)">续租</el-button>
          <el-button  @click="handleDelete(scope.row)" color="#fab6b6">注销</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin: 10px 0">
      <el-pagination
        v-model:currentPage="currentPage"
        :page-sizes="[5, 10]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import request from "../../untils/request";

export default {
  name: "userDockerManage",
  data() {
    return {
      addDialogVisible: false,
      reletDialogVisible: false,
      deleteDialogVisible: false,
      reminderDialogVisible: false,
      accessDialogVisible:false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      tableData: [],
      authorizationTableData: [],
      newAccess: undefined,
      form: {}, //某行数据
      addForm: {}, //新增Docker
      reletForm: {}, //续租
      deleteForm: {}, //注销
      authorizationForm: {}, //访问权限行数据
      reminder: {
        first: "记住您的Docker连接端口",
        second: "在您的命令行工具中使用ssh命令尝试与Docker进行连接:\n目标IP: 192.168.88.137\n目标端口: (Docker连接端口)",
        remark: "用户名: root\n默认密码: 12345678\n若连接失败可能Docker正在创建,请稍后重试或联系运维人员",
      },
      osOptions: [{
        value: 'ubuntu',
        label: 'Ubuntu'
      }, {
        value: 'centos',
        label: 'CentOS',
      }],
      versionOptions: [],
      accessOptions: [],
      ubuntuVersion:[{
        value: '20.04',
        label: '20.04'
      }, {
        value: '22.04',
        label: '22.04',
      }, {
        value: 'C',
        label: '22.04（GCC，G++捆绑包）',
      },{
        value: 'Python',
        label: '22.04（Python捆绑包）',
      }],
      centosVersion:[{
        value: '7',
        label: '7'
      }, {
        value: '8',
        label: '8',
      }],
    }
  },
  created() {
    this.load();
  },
  methods: {
    access(){
      if(this.newAccess=== undefined){
        this.$message({
          type: "error",
          message: "用户ID不能为空",
        });
        return; // 终止方法的执行
      }
      this.$confirm("确定为该用户开放访问？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        request.get("/podAccess/addAuthorizedUser", {
          params: {
            dockerID: this.form.id,
            userID: this.newAccess,
          },
        }).then((res) => {
          if (res.code === 0) {
            this.$message({
              type: "success",
              message: "权限已开放",
            });
            this.accessDialogVisible = false;
            this.newAccess = undefined;
          } else {
            this.$message({
              type: "error",
              message: res.message,
            });
          }
        });
      }).catch(() => {
        this.$message({
          type: "info",
          message: "已取消",
        });
      });
    },
    find(search){
      request.get("/podAccess/viewUnauthorizedUser", {
        params: {
          dockerID: this.form.id,
          search: search,
        },
      }).then((res) => {
        if (res.code === 0) {
          this.accessOptions = res.data;
        } else {
          this.$message({
            type: "error",
            message: res.message,
          });
        }
      });
    },
    deletePod(){
      this.$confirm("Docker注销不可撤销？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        request.get("/pod/delete", {
          params: {
            dockerID: this.deleteForm.dockerID,
            password: this.deleteForm.password,
          },
        }).then((res) => {
          if (res.code === 0) {
            this.$message({
              type: "success",
              message: "注销成功",
            });
            this.deleteDialogVisible = false;
            this.load();
          } else {
            this.$message({
              type: "error",
              message: res.message,
            });
          }
        });
      }).catch(() => {
        this.$message({
          type: "info",
          message: "已取消",
        });
      });
    },
    relet(){
      request.get("/podRequest/relet", {
            params: {
              dockerID: this.reletForm.dockerID,
              applyTime: this.reletForm.applyTime,
            },
          }).then((res) => {
            if (res.code === 0) {
              this.$message({
                type: "success",
                message: "申请已提交",
              });
              this.reletDialogVisible = false;
              this.reletForm = {};
            } else {
              this.$message({
                type: "error",
                message: res.message,
              });
            }
          });
    },
    save() {
      request.post("/podRequest/request", this.addForm).then((res) => {
        if (res.code === 0) {
          this.$message({
            type: "success",
            message: "申请已提交",
          });
          this.addDialogVisible = false;
          this.addForm = {};
        } else {
          this.$message({
            type: "error",
            message: res.message,
          });
        }
      });
    },
    load() {
      request.get("/pod/viewMyPod", {
          params: {
            pageNum: this.currentPage,
            pageSize: this.pageSize,
          },
        })
        .then((res) => {
          this.tableData = res.data.records;
          this.total = res.data.total;
        });
    },
    loadAuthorization() {
      request.get("/podAccess/viewPodAuthorization", {
        params: {
          dockerID: this.form.id,
        },
      }).then((res) => {
        this.authorizationTableData = res.data
      });
    },
    osChange(val) {
      if (val === "ubuntu") {
        this.versionOptions = this.ubuntuVersion;
      }
      if (val === "centos") {
        this.versionOptions = this.centosVersion;
      }
    },
    formatOS(row){
      if (row.imageOS === "ubuntu") {
        return "Ubuntu";
      }
      if (row.imageOS === "centos") {
        return "CentOS";
      }
    },
    formatVersion(row){
      if (row.imageOS === "ubuntu" && row.imageVersion === "C") {
        return "22.04（GCC，G++捆绑包）";
      }
      if (row.imageOS === "ubuntu" && row.imageVersion === "Python") {
        return "22.04（Python捆绑包）";
      }
      return row.imageVersion;
    },
    formatTime(row){
      return row.expirationTime.split('T')[0];
    },
    handleAccess(row){
      this.form = JSON.parse(JSON.stringify(row));
      this.accessDialogVisible = true;
      this.loadAuthorization();
    },
    handleRelet(row) {
      this.form = JSON.parse(JSON.stringify(row));
      this.reletDialogVisible = true;
      this.reletForm.podName=this.form.name;
      this.reletForm.dockerID=this.form.id;
    },
    handleDeleteAuthorized(row) {
      this.authorizationForm = JSON.parse(JSON.stringify(row));
      this.$confirm("确定回收该用户访问权限？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        request.get("/podAccess/deleteAuthorizedUser", {
          params: {
            ID: this.authorizationForm.id,
          },
        }).then((res) => {
          if (res.code === 0) {
            this.$message({
              type: "success",
              message: "权限已回收",
            });
            this.accessDialogVisible = false;
            this.authorizationForm = {};
          } else {
            this.$message({
              type: "error",
              message: res.message,
            });
          }
        });
      }).catch(() => {
        this.$message({
          type: "info",
          message: "已取消",
        });
      });
    },
    handleDelete(row) {
      this.form = JSON.parse(JSON.stringify(row));
      this.deleteDialogVisible = true;
      this.deleteForm.podName=this.form.name;
      this.deleteForm.dockerID=this.form.id;
    },
    handleSizeChange(pageSize) {
      //改变当前每页的个数触发
      this.pageSize = pageSize;
      this.load();
    },
    handleCurrentChange(pageNum) {
      //改变当前页码触发
      this.currentPage = pageNum;
      this.load();
    },
  },
};
</script>

<style scoped lang="less">
/deep/ .el-input {
  width: 85%;
}

/deep/ .el-dialog {
  background: #fcf9f4;
}

/deep/.el-form-item {
  margin-bottom: 30px;
}
</style>
